package com.ktjy.springsecuritydemo.config;

import com.ktjy.springsecuritydemo.handle.MyAuthenticationSuccessHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public PasswordEncoder getPw(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http)throws Exception{
        http.formLogin(formLoginSpec->formLoginSpec.usernameParameter("user").passwordParameter("pwd").loginPage("/tologin").loginProcessingUrl("/doLogin")
//                .successForwardUrl("/toMain")
                        .successHandler(new MyAuthenticationSuccessHandler("http://www.baidu,com"))
                .failureForwardUrl("/toError").permitAll()
        );

        http.authorizeHttpRequests((authz)-> authz.requestMatchers("/tologin").permitAll().requestMatchers("/toError").denyAll().anyRequest().authenticated()).httpBasic(Customizer.withDefaults());

        http.csrf(AbstractHttpConfigurer::disable);

        return http.build();
    }
}
